<template>
  <div class="app-container" v-loading="loading">
    <div class="flex flex-wrap">
      <div class="flex justify-between w-full p-b-5">
        <div class="font-black text-xl"><!-- 行业大客户新签合同额 --></div>
        <el-row :gutter="10" class="min-w-12/24" justify="end">
          <el-col :span="7">
            <el-date-picker
              style="width: 100%"
              v-model="queryParams.dateArr"
              type="daterange"
              range-separator="-"
              value-format="YYYY-MM-DD"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="getData"
            />
          </el-col>
          <!-- <el-col :span="5">
            <el-select
              class="w-full"
              v-model="queryParams.fiscalStatementType"
              placeholder="报表类型"
              @change="getData"
            >
              <el-option
                v-for="item in fiscal_statement_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              /> </el-select
          ></el-col> -->
          <!-- <el-col :span="5">
            <el-tree-select
              class="w-full"
              :disabled="userStore.userInfo.orgId != 484"
              v-model="queryParams.deptIdArr"
              placeholder="请选择公司"
              default-expand-all
              multiple
              :data="companyOption"
              :props="{
                value: 'id',
                label: 'label',
                children: 'children'
              }"
              @change="getData"
            />
          </el-col> -->
          <!-- <el-col :span="5">
            <el-select
              class="w-full"
              v-model="queryParams.isTax"
              placeholder="是否含税"
              @change="getData"
            >
              <el-option
                v-for="item in yes_or_no"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              /> </el-select
          ></el-col> -->
          <el-col :span="3" class="text-right">
            <el-button
              icon="Download"
              @click="exportExcel('行业大客户新签合同额')"
              >导出</el-button
            >
          </el-col>
        </el-row>
      </div>
      <div class="h-480px w-10/24">
        <EcharsPie :pieObj="pieObj" />
      </div>
      <div class="w-14/24">
        <el-table
          ref="industryTable"
          :data="tableData"
          style="width: 100%"
          border
          stripe
          :show-summary="false"
          :sum-text="'统计'"
        >
          <!-- @row-click="rowClick" -->
          <el-table-column
            type="index"
            label="排名"
            align="center"
            width="60"
          />
          <el-table-column
            v-for="(item, index) in tableLevel"
            :key="index"
            :prop="
              item.children && item.children.length ? undifined : item.prop
            "
            v-bind="item"
          >
            <template v-if="item.children && item.children.length">
              <el-table-column
                v-for="(item1, index1) in item.children"
                :key="index1"
                v-bind="item1"
              >
              </el-table-column>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script setup name="IndustryTable">
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import EcharsPie from './pie'
import { order_business_type } from '@/hooks/dict/order'
import { signedContractAmount } from '@/api/keyAccountSales/index'
import {
  companyOption //所属公司
} from '@/hooks/dict/order'
import { myToFixed } from '@/utils/commo'
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const {
  bidding_unit,
  fiscal_statement_type //是否
} = proxy.useDict('bidding_unit', 'fiscal_statement_type')
const data = reactive({
  queryParams: {
    dateArr: []
  },
  pieObj: {},
  tableData: [],

  orderBusinessType: []
})
let { queryParams, pieObj, tableData, orderBusinessType } = toRefs(data)

watchEffect(
  () => {
    if (order_business_type.value.length > 0) {
      let types = toRaw(order_business_type.value)
      orderBusinessType.value = types.filter(e => e.parentId == '财税-培训产业')
      // console.log('orderBusinessType.value', orderBusinessType.value)
    }
  },
  { flush: 'post' }
)
function goTo(url, data) {
  router.push({ path: url, query: data })
}
// 点击行业大客户新签合同额行
// function rowClick(row, column, event) {
//   let priceObj = {
//     标准版会员: 260,
//     增强版会员: 299,
//     专业版会员: 399
//   }
//   let obj = {
//     receiptsDates: queryParams.value.dateArr,
//     productName: '云财税',
//     price: priceObj[row.businessType]
//     // businessType: row.businessType
//   }
//   // console.log('obj==>', obj)
//   // goTo('/sales/indent/salesOrder', { salesOrderData: JSON.stringify(obj) })
// }
const tableLevel = ref([
  {
    show: true,
    prop: 'orgId',
    label: '分公司',
    align: 'center',
    width: 160,
    showOverflowTooltip: true,
    formatter: row => {
      return proxy.selectDictLabel(bidding_unit.value, row.orgId)
    }
  },
  {
    show: true,
    prop: 'targetValue',
    label: '指标(万元)',
    align: 'center',
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'nowAmount',
    label: '完成情况(万元)',
    align: 'center',
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'allPercent',
    label: '全省完成率',
    align: 'center',
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'chronicle',
    label: '序时进度',
    align: 'center',
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'lastYearAmount',
    label: computed(() => {
      return `去年${
        queryParams.value.dateArr &&
        queryParams.value.dateArr.length > 0 &&
        queryParams.value.dateArr[0]
          ? proxy.parseTime(queryParams.value.dateArr[0], '{m}') - 0
          : 1
      }-${
        queryParams.value.dateArr &&
        queryParams.value.dateArr.length > 0 &&
        queryParams.value.dateArr[1]
          ? proxy.parseTime(queryParams.value.dateArr[1], '{m}') - 0
          : new Date().getMonth() + 1
      }月完成值`
    }),
    align: 'center',
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'yoypercent',
    label: '同比',
    align: 'center',
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'lastMonthAmount',
    label: computed(() => {
      return `${
        queryParams.value.dateArr &&
        queryParams.value.dateArr.length > 0 &&
        queryParams.value.dateArr[0]
          ? proxy.parseTime(queryParams.value.dateArr[0], '{m}') - 1
          : 1
      }-${
        queryParams.value.dateArr &&
        queryParams.value.dateArr.length > 0 &&
        queryParams.value.dateArr[1]
          ? proxy.parseTime(queryParams.value.dateArr[1], '{m}') - 1
          : new Date().getMonth()
      }月完成值`
    }),
    align: 'center',
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'qoqpercent',
    label: '环比',
    align: 'center',
    showOverflowTooltip: true
  }
])

const loading = ref(false)
// 行业大客户新签合同额
function getData() {
  let sxjdData = []
  let qswclData = []
  let wclData = []
  let xName = []
  loading.value = true
  signedContractAmount(queryParams.value)
    .then(res => {
      loading.value = false
      // console.log('', res.data)
      tableData.value = res.data
      res.data.forEach(item => {
        xName.push(proxy.selectDictLabel(bidding_unit.value, item.orgId))
        sxjdData.push(item.chronicle.replace('%', ''))
        qswclData.push(item.allPercent.replace('%', ''))
        wclData.push(myToFixed((item.nowAmount / item.targetValue) * 100, 2))
      })

      pieObj.value.option = {
        legend: {
          data: ['时序进度', '全省完成率', '完成率']
        },
        xAxis: {
          type: 'category',
          axisLabel: { interval: 0, rotate: 30 },
          data: xName
        },
        yAxis: {
          type: 'value',
          name: '单位(%)'
        },
        series: [
          {
            name: '时序进度',
            data: sxjdData,
            type: 'line'
          },
          {
            name: '全省完成率',
            data: qswclData,
            type: 'line'
          },
          {
            name: '完成率',
            data: wclData,
            type: 'bar',
            label: {
              show: true,
              position: 'top'
            }
          }
        ]
      }
    })
    .catch(() => {
      loading.value = false
    })
}
getData()

const showColu = ref(true)
// 前端导出excel
const exportExcel = excelName => {
  let tableBox = {
    expireTable: '服务到期人数分析',
    levelTable: '地市统计分析',
    industryTable: '行业大客户新签合同额'
  }
  let tableRef = ''
  for (let key in tableBox) {
    console.log('导出key==>', key)
    if (tableBox[key] === excelName) {
      tableRef = key
    }
  }
  showColu.value = false
  setTimeout(() => {
    try {
      const $e = proxy.$refs[tableRef].$el
      let $table = $e.querySelector('.el-table__fixed')
      if (!$table) {
        $table = $e
      }

      const wb = XLSX.utils.table_to_book($table, { raw: true })
      const wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      FileSaver.saveAs(
        new Blob([wbout], { type: 'application/octet-stream' }),
        `${excelName}.xlsx`
      )
      showColu.value = true
    } catch (e) {
      showColu.value = true
      if (typeof console !== 'undefined') console.error(e)
    }
  }, 500)
}
</script>
<style lang="scss" scoped>
.el-radio-group.groupBtn :deep(.el-radio__input) {
  display: none;
}
</style>
